package com.zq.solution.listnode;

import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName DetectCycle
 * @Description
 * @Author ZQ
 * @Date 2020/10/10 10:18
 * @Version 1.0
 */
public class DetectCycle {
    public ListNode<Integer> detectCycle(ListNode<Integer> head) {
        ListNode<Integer> pos = head;
        Set<ListNode<Integer>> visited = new HashSet<>();
        while (pos != null) {
            if (visited.contains(pos)) {
                return pos;
            } else {
                visited.add(pos);
            }
            pos = pos.next;
        }
        return null;
    }
}
